package mspbots.autotask.data.core.contacts;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import mspbots.autotask.data.core.AbstractToolsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;

/**
 * mspbots.core.sync.autotask.badmessage.BadMessageReceiver
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/7/21
 */
@Log4j2
@Component
@RequiredArgsConstructor
public class ContactsReceiver extends AbstractToolsUtil {

    private final ContactsRepository contactsRepository;

    @RabbitListener(queues = "auto-task.contacts.sync")
    public void syncTask(ResultMsg content) {

        Contact contact = Contact.builder().otherId(content.getId())
                .tenantId(content.getTenantId())
                .syncTime(content.getSyncDate())
//                .createdTime(ObjectUtils.isEmpty(content.getEntity().get("createDate"))
//                        || "null".equalsIgnoreCase(content.getEntity().get("createDate").asText())
//                        ? null:
//                        LocalDateTime.parse(content.getEntity().get("createDate").textValue(),DateTimeFormatter.ISO_OFFSET_DATE_TIME))
//                .updatedTime(ObjectUtils.isEmpty(content.getEntity().get("lastActivityDate"))
//                        || "null".equalsIgnoreCase(content.getEntity().get("lastActivityDate").asText())
//                        ? null:
//                        LocalDateTime.parse(content.getEntity().get("lastActivityDate").textValue(),DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .entity(content.getEntity())
                .build();

        if (ObjectUtils.isEmpty(contact.getOtherId())) {
            return;
        }

        this.contactsRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(ticket -> {
                    contact.setId(ticket.getId());
                    return contact;
                })
                .defaultIfEmpty(contact)
                .flatMap(this.contactsRepository::save)
                .block(Duration.ofSeconds(10));

    }

}
